package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Override
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart queryShoppingCart =new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,queryShoppingCart);
        queryShoppingCart.setUserId(BaseContext.getCurrentId());
        log.info("[添加购物车] shoppingCart:{}",queryShoppingCart);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectByAll(queryShoppingCart);
        ShoppingCart dpShoppingCart =null;
        if (shoppingCartList !=null && shoppingCartList.size()>0){
            dpShoppingCart = shoppingCartList.get(0);
            dpShoppingCart.setNumber(dpShoppingCart.getNumber()+1);
            shoppingCartMapper.updateShoppingCartById(dpShoppingCart);
        }else {
            Long dishId = queryShoppingCart.getDishId();
            if (dishId !=null){
                Dish dish = dishMapper.selectByID(dishId);
                queryShoppingCart.setName(dish.getName());
                queryShoppingCart.setImage(dish.getImage());
                queryShoppingCart.setAmount(dish.getPrice());
            }else {
                SetmealVO setmealVO =  setmealMapper.selectById(queryShoppingCart.getSetmealId());
                queryShoppingCart.setName(setmealVO.getName());
                queryShoppingCart.setImage(setmealVO.getImage());
                queryShoppingCart.setAmount(setmealVO.getPrice());
            }
            queryShoppingCart.setNumber(1);
            queryShoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insertShoppingCart(queryShoppingCart);
        }

    }

    @Override
    public List<ShoppingCart> selectCatr() {
        ShoppingCart queryShoppingCart =new ShoppingCart();
        queryShoppingCart.setUserId(BaseContext.getCurrentId());
        return shoppingCartMapper.selectByAll(queryShoppingCart);
    }

    @Override
    public void deleteCart() {
        shoppingCartMapper.deleteCart(BaseContext.getCurrentId());
    }
}
